//
//  ViewController.m
//  NSOperation
//
//  Created by 伍银荣 on 2021/8/26.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
//创建全局队列
@property (nonatomic, strong) NSOperationQueue *queue;

@end

@implementation ViewController
//懒加载
- (NSOperationQueue *)queue {
    if (!_queue) {
        _queue = [[NSOperationQueue alloc]init];
    }
    return _queue;
}

/**
   1.NSOperation是一个抽象类,不能直接使用,方法没有实现.
   2.约束子类都有同样的属性和方法
   3.NSOperation的子类:
 1> NSInvocationOperation
 2> NSBlockOperation
 3> 自定义operation
   4.NSOperationQueue:队列
 */

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   // [self demo3];
    
    //模拟当图片下载完成后回归到主线层上更新UI
    [self.queue addOperationWithBlock:^{
        NSLog(@"异步下载图片");
        //获取当前队列
        [NSOperationQueue currentQueue];
        //回归到主线程上更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            NSLog(@"更新UI");
        }];
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //创建操作
    NSInvocationOperation *op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(demo) object:nil];
    //操作开启
//    [op start];  //不开启新线程,更新操作的状态
//    [op start];
//    [op start];
    //创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    //将操作添加到队列中
    [queue addOperation:op];  //这种方法创建了新的线程
}

- (void)demo {
    NSLog(@"--%@",[NSThread currentThread]);
}

//使用NSBlockOperation对象创建操作
- (void)demo2 {
    //创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    //创建操作
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
        //这样写创建了新的线程
        NSLog(@"hello--%@",[NSThread currentThread]);
    }];
    //把操作添加到队列中
    [queue addOperation:op];
}

- (void)demo3 {
    //使用全局队列,相当于GCD中的并发队列异步执行
    for (int i = 0; i < 10; i++) {
        [self.queue addOperationWithBlock:^{
            NSLog(@"hello -%d - %@",i, [NSThread currentThread]);
        }];
    }
}

@end
